const moment = require('moment'); 
//model 数据层
module.exports = class testModel extends require('./Model') {
    //多条件查找口味
    // static findFlavorByCon(req, res) {
    //     return new Promise((resolve, reject) => {
    //         let conditions = req.body;
    //         console.log(conditions)
    //         let sql = 'SELECT * FROM baking_flavor WHERE ';
    //         let params = [];
    
    //         // 构建查询条件
    //         let clauses = [];
    //         if (conditions.name) {
    //             clauses.push('name LIKE ?');
    //             params.push(`%${conditions.name}%`);
    //         }
    //         if (conditions.id) {
    //             clauses.push('id = ?');
    //             params.push(conditions.id);
    //         }
    //         if (conditions.cate_id) {
    //             clauses.push('good_id = ?');
    //             params.push(conditions.cate_id);
    //         }
    //         if (conditions.status) {
    //             clauses.push('remark = ?');
    //             params.push(conditions.status);
    //         }
    
    //         if (clauses.length > 0) {
    //             sql += clauses.join(' AND ');
    //         } else {
    //             sql = 'SELECT * FROM baking_flavor';
    //         }
    
    //         this.query(sql, params) // 调用基类的 query 方法执行 SQL 语句
    //             .then((r) => {
    //                 resolve(r);
    //             })
    //             .catch((e) => {
    //                 reject(e);
    //             });
    //     })
        
    // }
    static findFlavorByCon(req, res) {
        return new Promise((resolve, reject) => {
            let conditions = req.body;
            console.log('Conditions:', conditions); // 添加日志
            let sql = 'SELECT bg.id, bg.name AS good_name, bg.cover_img, bf.name AS flavor_name, bf.remark, bf.create_time, bf.update_time, bf.cook, bf.shicai FROM baking_good bg JOIN baking_flavor bf ON bg.id = bf.good_id WHERE ';
            let params = [];
    
            // 构建查询条件
            let clauses = [];
            if (conditions.name) {
                clauses.push('bf.name LIKE ?');
                params.push(`%${conditions.name}%`);
            }
            if (conditions.id) {
                clauses.push('bg.id = ?');
                params.push(conditions.id);
            }
            if (conditions.cate_id) {
                clauses.push('bg.cate_id = ?');
                params.push(conditions.cate_id);
            }
            if (conditions.status) {
                clauses.push('bf.remark = ?');
                params.push(conditions.status);
            }
    
            if (clauses.length > 0) {
                sql += clauses.join(' AND ');
            } else {
                sql = 'SELECT bg.id, bg.name AS good_name, bg.cover_img, bf.name AS flavor_name, bf.remark, bf.create_time, bf.update_time, bf.cook, bf.shicai FROM baking_good bg JOIN baking_flavor bf ON bg.id = bf.good_id';
            }
    
            console.log('Executing SQL:', sql, 'with params:', params); // 添加日志
            this.query(sql, params) // 调用基类的 query 方法执行 SQL 语句
                .then((r) => {
                   // console.log('Query result:', r); // 添加日志
                    resolve(r);
                })
                .catch((e) => {
                   // console.error('Database query error:', e); // 添加日志
                    reject(e);
                });
        });
    }

    //增加口味数据
    static addFlavor(req, res) {
        return new Promise((resolve, reject) => {
            let info = req.body;
            const currentTime = moment().format('YYYY-MM-DD HH:mm:ss'); // 当前时间

            // 设置 created_time 和 updated_time
            info.create_time = currentTime;
            info.update_time = currentTime;
            let sql = 'INSERT INTO baking_flavor SET ?';
    
            this.query(sql, info)
                .then((r) => {
                    // 成功添加数据
                    res.send({ status: 1, message: 'ok', successMessage: '新增口味成功！' });
                })
                .catch((e) => {
                    // 处理错误
                    res.send({ status: 0, message: 'error', errorMessage: '新增口味失败！' });
                });
        });
    }


    //修改分类信息
    //注意mysql配置是默认不识别大小写的，可以对mysql字段中的排序规则设置为 utf8mb4_bin 这样mysql中你要修改的字段就可以实现区分大小
    static updateFlavor(req, res) {
        return new Promise((resolve, reject) => {
            // 前端传参可以通过body传name和newName来进行修改
            let info = req.body
            //sql 语句为 当name是xx的时候，把name修改为xxx
            let sql = 'UPDATE baking_flavor SET ? WHERE id = ?'
            this.query(sql, [info, info.id])
                .then((r) => {
                    res.send({status:1,message:'ok',successMessage:'修改成功！'})
                })
                .catch((e) => {
                    res.send({status:0,message:'error',errorMessage:'修改失败！'})
                })
        })
    }

    // 删除分类信息
    static async deleteFlavor(req, res) {
        const { id } = req.body; // 假设 id 是通过 URL 参数传递的
        console.log(id)
        const sql = 'DELETE FROM baking_flavor WHERE id = ?';

        try {
            const result = await this.query(sql,id);
            if (result.affectedRows === 1) {
                res.json({ status: 1, message: 'ok', successMessage: '删除成功！' });
            } else {
                res.status(404).json({ status: 0, message: 'error', errorMessage: '未找到404' });
            }
        } catch (error) {
            res.status(500).json({ status: 0, message: 'error', errorMessage: '删除失败！' });
            console.log(result)
        }
    }
}